from pathlib import Path
import sys
import argparse

'''
	编码：utf-8
	功能：模拟linux下的ls命令
	日期：2024/3/12
	作者：码鸽
	测试用例：
		通过的结果为成功的用例：
			ls
			ls .
			ls ./
			ls \
			ls existing_path
			ls non-existing_path
			ls existing_path/
			ls non-existing_path/
			ls ./existing_path/
			ls ./non-existing_path/
			ls existing_path./ -a  （abspath估计能够修正奇怪的路径写法）
		通过的结果为失败的用例：
			
		未通过：
			ls existing_path./  （没想到os.listdir能接收这么奇葩的参数）
			ls existing_path./ -r

'''
def handler_exception(func):
	'''
		# 功能：	用try-except块包起函数体，实现递归函数的错误处理，
				使递归函数仅仅跳过当前函数栈，而不止于终止整个递归进程

		# 注： 不知道为什么没有用
	'''
	def wrapper(*args, **kwargs):
		try:
			func(*args, **kwargs)
		except Exception as e:
			print(e, file=sys.stderr)
			return

	return func


def is_path_contains_space(path):
	'''
		# 功能：判断path路径是否含有空格
		# 参数：
			path：类型为pathlib.Path对象
	'''
	parts = path.parts
	for part in parts:
	    if ' ' in part:
	        return True
	return False


# def warp_up_with_dquote(input_string):
# 	return "\"" + input_string + "\""

# @handler_exception
def list_files_and_dirs(path, absolute_path=False, only_dirs=False, only_files=False, recursive=False):
	try:
		if not path.exists():
			print(f"[Error] 路径\"{path}\"不存在！", file=sys.stderr)
			exit(-1)
		for p in path.iterdir():
			if (only_dirs and not p.is_dir()) or (only_files and not p.is_file()):
				continue
			if absolute_path:
				p = p.absolute()

			if is_path_contains_space(p):
				print(f"\"{p}\"")
			else:
				print(p)

			if p.is_dir() and recursive:
				list_files_and_dirs(p, absolute_path, only_dirs, only_files, recursive)
	except Exception as e:
		print(e)

	 

def ls():
	# ====================================================================================
	# ---- <begin> 命令参数设置 -----------------------
	parser = argparse.ArgumentParser(description="List files and directories.")
	group = parser.add_mutually_exclusive_group()
	group.add_argument("-d", "--directories", action="store_true", help="List only directories.")
	group.add_argument("-f", "--files", action="store_true", help="List only files.")
	group.add_argument("-r", "--recursive", action="store_true", help="Recursively list files and directories.")
	parser.add_argument("path", nargs="?", default=".\\", help="Path to the directory.")
	parser.add_argument("-a", "--absolute", action="store_true", help="Print absolute paths.")

	args = parser.parse_args()

	# ---- <end> 命令参数设置 -------------------------
	# ====================================================================================

	path = Path(args.path)
	list_files_and_dirs(path, args.absolute, args.directories, args.files, args.recursive)


if __name__ == "__main__":
    ls()